/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-06-17 18:06:34
 * @Description: 第四步 -- 管理员填写
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  ScrollView,
  NativeModules,
  SafeAreaView,
  TouchableOpacity,
  PixelRatio
} from 'react-native';
import { Button, cache, msg, FormInput, AsyncStorage } from '@/common';
import {
  px2dp, priceColor, mainBgColorWhite, fontColorBlack,
  fontColorDeepGray, mainBgColorLightGray, mainBgColorBlack,
} from '@/styles';
import { iconAdd } from '@/images';
import { uploadImage } from '@/config';
import businessApi from '@/api/business';

const { Submit } = Button;

export default class BusinessManageSetCerti extends React.Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    this.state = {
      name: '',
      mobile: '',
      idNo: '',
      file: '',
      legalInfo: {},
      idCard: {},
      bankcard: {},
      routerFrom
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.BUSINESS_INFO_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { businessInfoCerti } = dataCache;
      this.setState({ legalInfo: businessInfoCerti });
    }).catch(err => {
      console.log('企业信息反写异常：', err);
    });
    AsyncStorage.getItem(cache.LEGAL_INFO_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { legalInfoCerti } = dataCache;
      this.setState({ idCard: legalInfoCerti });
    }).catch(err => {
      console.log('法人信息反写异常：', err);
    });

    AsyncStorage.getItem(cache.CORPORATE_ACCOUNT_INFO_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { CorporateAccountInfoCerti } = dataCache;
      this.setState({ bankcard: CorporateAccountInfoCerti });
    }).catch(err => {
      console.log('对公账户信息反写异常：', err);
    });

    AsyncStorage.getItem(cache.BUSINESS_MANAGE_SET_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { BusinessManageSetCerti } = dataCache;
      this.setState({ ...BusinessManageSetCerti });
    }).catch(err => {
      console.log('企业管理员信息反写异常：', err);
    });

    this.getUserInfo();
  }

  render() {
    const { name, mobile, idNo, file } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.inner}>
          <Text style={styles.stepTip}>第四步</Text>
          <View style={styles.firstPart}>
            <FormInput
              label={this.formItem('管理员姓名')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入管理员姓名'
              defaultValue={name}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('name', value);
              }}
            // disabled
            />
            <FormInput
              // label={<>
              //   <Text style={{ color: priceColor }}>&nbsp;&nbsp;&nbsp;&nbsp;</Text>
              //   <Text style={{ color: fontColorDeepGray }}>电话号码</Text>
              // </>}
              label={this.formItem('电话号码')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入电话号码'
              defaultValue={mobile}
              inputType={1}
              maxLength={11}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('mobile', value);
              }}
            // disabled
            />

            <FormInput
              label={this.formItem('身份证号码')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入管理员身份证号码'
              defaultValue={idNo}
              inputType={1}
              maxLength={18}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('idNo', value);
              }}
            // disabled
            />
          </View>
          <View style={styles.licenseBox}>
            <View style={styles.labelBox}>{this.formItem('授权书')}</View>
            <View style={styles.licenseBtnBox}>
              <TouchableOpacity
                onPress={this.selectImage}
              >
                {
                  file ?
                    <Image
                      style={styles.licenseImgStyle}
                      source={{ uri: file }}
                    /> :
                    <View style={styles.defaultAddBox}>
                      <Image
                        style={styles.addImgIcon}
                        source={iconAdd}
                      />
                    </View>
                }
              </TouchableOpacity>
            </View>

          </View>
          <View style={styles.bottomBtnBox}>
            <View style={styles.submitBox}>
              <Submit
                text='上一步'
                btnTextStyle={styles.preStepText}
                boxStyle={styles.preBoxStyle}
                onClick={this.goBack}
              />
            </View>
            <View style={styles.submitBox}>
              <Submit
                text='提交'
                btnTextStyle={styles.nextStepText}
                boxStyle={styles.nextBoxStyle}
                onClick={this.submit}
              />
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  getUserInfo = () => {
    AsyncStorage.getUserInfo()
      .then((res) => {
        if (res && res.wholeMobile) {
          this.setState({ mobile: res && res.wholeMobile });
        }
      })
      .catch((error) => {
        console.log('error->', error);
      });
  }

  formItem = (value) => {
    return (
      <>
        <Text style={{ color: priceColor }}>＊</Text>
        <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>{value}</Text>
      </>
    );
  }

  goBack = () => {
    msg.emit('router: back');
  }

  submit = () => {
    const { name, mobile, idNo, file, legalInfo, idCard, bankcard, routerFrom } = this.state;
    if (!name) return msg.emit('app:tip', { text: '请填写管理员姓名' });
    if (!mobile) return msg.emit('app:tip', { text: '请填写手机号' });
    if (mobile.length !== 11) return msg.emit('app:tip', { text: '请填写正确的手机号' });
    if (!idNo) return msg.emit('app:tip', { text: '请填写身份证号' });
    if (idNo.length !== 15 && idNo.length !== 18) return msg.emit('app:tip', { text: '请填写正确的身份证号' });
    if (!file) return msg.emit('app:tip', { text: '请上传授权书' });
    const BusinessManageSetCertiCache = {
      name,
      idNo,
      file,
      mobile
    };
    const businessCertiString = JSON.stringify({
      BusinessManageSetCerti: BusinessManageSetCertiCache,
    });
    AsyncStorage.setItem(
      cache.BUSINESS_MANAGE_SET_CERTI,
      businessCertiString
    );
    const certiParams = {
      admin: BusinessManageSetCertiCache,
      legalInfo,
      idCard,
      bankcard
    };
    businessApi.addLegal(certiParams).then(res => {
      if (res.success) {
        msg.emit('router: goToNext', {
          routeName: 'BusinessCertiFeedBack',
          status: true,
          routerFrom
        });
      } else {
        msg.emit('router: goToNext', {
          routeName: 'BusinessCertiFeedBack',
          status: false,
          reason: res.msg,
          routerFrom
        });
      }
    });
  }

  // 输入框变化监听
  onChange = (type, value) => {
    this.setState({ [type]: value });
  }

  // 选择图片
  selectImage = () => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(path);
    });
  }

  // 上传图片
  IdCardUpload(path) {
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '图片上传中...',
      icon: 'loading',
    });
    uploadImage('upload?dirName=businessCert', path).then(res => {
      console.log(`uploadImage：${JSON.stringify(res)}`);
      if (res.success) {
        this.setState({ file: res.data.url });
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '上传失败，请重试',

          isClickBg: false,
          okFn: () => { },
        });
      }
      msg.emit('app:selfTip', {
        isVisible: false,
      });
    }).catch(err => {
      console.log(err);
      msg.emit('app:selfTip', {
        isVisible: false,
      });
      // 请求失败
      msg.emit('app:messageBox', {
        isVisible: true,
        title: '温馨提示',
        text: '上传出错，请重试',

        isClickBg: false,
        okFn: () => { },
      });
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray
  },
  stepTip: {
    color: mainBgColorBlack,
    fontSize: px2dp(28),
    paddingLeft: px2dp(32),
    paddingVertical: px2dp(24)
  },
  firstPart: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40)
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38)
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline'
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130)
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  longTimeBox: {
    flexDirection: 'row',
    marginRight: px2dp(40)
  },
  longTime: {
    color: '#b2b2b2',
    marginLeft: px2dp(16)
  },
  itemBox: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ebebeb',
    width: '100%',
    height: 60,
  },
  labelBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190)
  },
  addressBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(10)
  },
  addressImgBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  iconMore: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(16)
  },
  timeImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(16)
  },
  licenseBox: {
    justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    marginTop: px2dp(24),
  },
  licenseBtnBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190),
    marginTop: px2dp(40),
    paddingLeft: px2dp(32)
  },
  licenseImgStyle: {
    width: px2dp(160),
    height: px2dp(160),
  },
  defaultAddBox: {
    width: px2dp(160),
    height: px2dp(160),
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(8),
  },
  addImgIcon: {
    width: px2dp(48),
    height: px2dp(48)
  },
  bottomBtnBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: px2dp(40),
    height: px2dp(200),
  },
  submitBox: {
    flex: 1,
    alignItems: 'center'
  },
  preStepText: {
    fontSize: px2dp(32),
    color: '#686764'
  },
  nextStepText: {
    fontSize: px2dp(32),
  },
  preBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
    backgroundColor: '#E6E6E5'
  },
  nextBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
  },
  addressText: {
    color: '#b2b2b2',
    maxWidth: '80%'
  }
});
